﻿using System;
using System.IO;
using System.Xml;
using System.Data;
using System.Configuration;
using System.Web;
using System.Collections.Specialized;
using SyCODE.Component;
using SyCODE.Component.Security;
using SyCODE.Component.DataFactory;
using System.Text;
using System.Web.Security;

namespace SyCODE.Blog
{
    /// <summary>
    /// SetAlbum 的摘要说明
    /// </summary>
    public class SetAlbum : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
			Ticket ticket = Ticket.Get(FormsAuthentication.FormsCookieName);
            if (Ticket.Authenticate(ticket))
            {
                string path = Path.Combine(AppPath.GetUserPhysicalPath(ticket.Name), "album.xml");

                XmlDocument albumDom = new XmlDocument();
                albumDom.Load(path);

                switch (context.Request.Form["active"])
                {
                    case "0":
                        AddAlbum(albumDom, context.Request.Form["name"], ticket.Name);
                        break;
                    case "1":
                        RenameAlbum(albumDom, context.Request.Form["idx"], context.Request.Form["name"]);
                        break;
                    case "2":
                        RemoveAlbum(albumDom, context.Request.Form["idx"], ticket.Name);
                        break;
                    case "3":
                        SetCover(albumDom, context.Request.Form["idx"], context.Request.Form["cover"], ticket.Name);
                        break;
                    case "4":
                        RemovePhoto(albumDom, context.Request.Form["idx"], context.Request.Form["photo"], ticket.Name);
                        break;
                    case "5":
                        MovePhoto(albumDom, context.Request.Form["idx"], context.Request.Form["to"], context.Request.Form["photo"], ticket.Name);
                        break;
                    case "6":
                        RenamePhoto(albumDom, context.Request.Form["idx"], context.Request.Form["photo"], context.Request.Form["name"]);
                        break;
                }

                albumDom.Save(path);
            }
            else
            {
                Function.ClientAlert(StringResource.GetField("authfaild"));
            }
        }

        private void AddAlbum(XmlDocument albumDom, string name, string user)
        {
            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("u", user);
            DBAM dbam = new DBAM();
            try
            {
                dbam.BuildParameters("createalbum", nvc);
                if (dbam.Execute() > 0)
                {
                    string id = ((int)dbam.GetResult()).ToString();
                    string path = Path.Combine(AppPath.GetUserPhysicalPath(user), @"album\comment\" + id + @"\");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    XmlTextWriter writer = new XmlTextWriter(File.Create(Path.Combine(path, "main.xml")), Encoding.UTF8);
                    writer.WriteStartDocument();
                    writer.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='/ui/common/container2.xsl'");

                    writer.WriteStartElement("html");

                    writer.WriteStartElement("head");

                    writer.WriteStartElement("meta");
                    writer.WriteAttributeString("http-equiv", "Content-Type");
                    writer.WriteAttributeString("content", "text/html; charset=utf-8");
                    writer.WriteEndElement();

                    writer.WriteStartElement("title");
                    writer.WriteString(name + " - Powered By X3BLOG");
                    writer.WriteEndElement();

                    writer.WriteEndElement();

                    writer.WriteStartElement("body");
                    writer.WriteEndElement();

                    writer.WriteEndElement();

                    writer.WriteEndDocument();

                    writer.Flush();
                    writer.Close();

                    XmlElement album = albumDom.CreateElement("a");
                    album.SetAttribute("id", id);
                    album.SetAttribute("href", "album/comment/" + id + "/");
                    album.SetAttribute("name", name);
                    album.SetAttribute("cover", "0");

                    albumDom.DocumentElement.SelectSingleNode("body").AppendChild(album);
                }
            }
            finally
            {
                dbam.Dispose();
            }
        }

        private void RenameAlbum(XmlDocument albumDom, string idx, string name)
        {
            albumDom.DocumentElement.SelectSingleNode("body").ChildNodes[Int32.Parse(idx)].Attributes["name"].Value = name;
        }

        private void RemoveAlbum(XmlDocument albumDom, string idx, string user)
        {

            XmlNode body = albumDom.DocumentElement.SelectSingleNode("body");
            XmlNode sourceAlbum = body.ChildNodes[Int32.Parse(idx)];

            XmlNode targetAlbum = body.ChildNodes[0];

            for (int i = sourceAlbum.ChildNodes.Count; i > 0; )
            {
                targetAlbum.AppendChild(sourceAlbum.ChildNodes[--i]);
            }

            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("u", user);
            nvc.Add("id", sourceAlbum.Attributes["id"].Value);
            nvc.Add("count", targetAlbum.ChildNodes.Count.ToString());
            if (targetAlbum.ChildNodes.Count > 0)
            {
                nvc.Add("cover", targetAlbum.ChildNodes[Int32.Parse(targetAlbum.Attributes["cover"].Value)].Attributes["src"].Value);
            }
            else
            {
                nvc.Add("cover", "");
            }

            DBAM dbam = new DBAM();

            try
            {
                dbam.BuildParameters("deletealbum", nvc);
                dbam.Execute();

                body.RemoveChild(sourceAlbum);
            }
            finally
            {
                dbam.Dispose();
            }
        }

        private void UpdateAlbum(NameValueCollection nvc)
        {
            DBAM dbam = new DBAM();
            try
            {
                dbam.BuildParameters("updatealbum", nvc);
                dbam.Execute();
            }
            finally
            {
                dbam.Dispose();
            }
        }

        private void SetCover(XmlDocument albumDom, string idx, string cover, string user)
        {
            XmlNode album = albumDom.DocumentElement.SelectSingleNode("body").ChildNodes[Int32.Parse(idx)];
            album.Attributes["cover"].Value = cover;

            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("u", user);
            nvc.Add("id", album.Attributes["id"].Value);
            nvc.Add("count", album.ChildNodes.Count.ToString());
            nvc.Add("cover", album.ChildNodes[Int32.Parse(cover)].Attributes["src"].Value);

            UpdateAlbum(nvc);
        }

        private void RemovePhoto(XmlDocument albumDom, string idx, string photo, string user)
        {
            string path = Path.Combine(AppPath.GetUserPhysicalPath(user), @"album\");
            XmlNode album = albumDom.DocumentElement.SelectSingleNode("body").ChildNodes[Int32.Parse(idx)];
            XmlNodeList photos = album.ChildNodes;
            int cover = Int32.Parse(album.Attributes["cover"].Value);
            string[] indexs = photo.Split(',');

            for (int i = indexs.Length; i > 0; )
            {
                int index = Int32.Parse(indexs[--i]);

                XmlNode photoNode = photos[index];
                string img = HttpUtility.UrlDecode(photoNode.Attributes["src"].Value);

                if (index == cover)
                {
                    album.Attributes["cover"].Value = "0";
                }

                File.Delete(Path.Combine(path, img));
                File.Delete(Path.Combine(path, @"thumb/" + img));

                album.RemoveChild(photoNode);
            }

            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("u", user);
            nvc.Add("id", album.Attributes["id"].Value);
            nvc.Add("count", album.ChildNodes.Count.ToString());
            if (album.ChildNodes.Count > 0)
            {
                nvc.Add("cover", album.ChildNodes[Int32.Parse(album.Attributes["cover"].Value)].Attributes["src"].Value);
            }
            else
            {
                nvc.Add("cover", "");
            }

            UpdateAlbum(nvc);
        }

        private void MovePhoto(XmlDocument albumDom, string idx, string to, string photo, string user)
        {
            XmlNode body = albumDom.DocumentElement.SelectSingleNode("body");
            XmlNode sourceAlbum = body.ChildNodes[Int32.Parse(idx)];
            XmlNode targetAlbum = body.ChildNodes[Int32.Parse(to)];
            XmlNodeList photos = sourceAlbum.ChildNodes;

            int cover = Int32.Parse(sourceAlbum.Attributes["cover"].Value);
            string[] indexs = photo.Split(',');

            for (int i = indexs.Length; i > 0; )
            {
                int index = Int32.Parse(indexs[--i]);

                targetAlbum.AppendChild(photos[index]);

                if (index == cover)
                {
                    sourceAlbum.Attributes["cover"].Value = "0";
                }
            }

            if (indexs.Length > 0)
            {
                NameValueCollection nvc = new NameValueCollection();
                nvc.Add("u", user);
                nvc.Add("from", sourceAlbum.Attributes["id"].Value);
                nvc.Add("to", targetAlbum.Attributes["id"].Value);

                nvc.Add("count", sourceAlbum.ChildNodes.Count.ToString());
                nvc.Add("count1", targetAlbum.ChildNodes.Count.ToString());

                if (sourceAlbum.ChildNodes.Count > 0)
                {
                    nvc.Add("cover", sourceAlbum.ChildNodes[Int32.Parse(sourceAlbum.Attributes["cover"].Value)].Attributes["src"].Value);
                }
                else
                {
                    nvc.Add("cover", "");
                }

                if (targetAlbum.ChildNodes.Count > 0)
                {
                    nvc.Add("cover1", targetAlbum.ChildNodes[Int32.Parse(targetAlbum.Attributes["cover"].Value)].Attributes["src"].Value);
                }
                else
                {
                    nvc.Add("cover1", "");
                }

                DBAM dbam = new DBAM();
                try
                {
                    dbam.BuildParameters("movephoto", nvc);
                    dbam.Execute();
                }
                finally
                {
                    dbam.Dispose();
                }
            }
        }

        private void RenamePhoto(XmlDocument albumDom, string idx, string photo, string name)
        {
            albumDom.DocumentElement.SelectSingleNode("body").ChildNodes[Int32.Parse(idx)].ChildNodes[Int32.Parse(photo)].Attributes["alt"].Value = name;
        }
    }
}